<template>
  <div class="health-dashboard">
    <!-- 顶部标题和日期 -->
    <div class="dashboard-header">
      <h1>{{ reportDate }} 健康日报</h1>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-edit" @click="goToDataLog">今日登记</el-button>
        <el-button type="text" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 主要指标卡片 -->
    <div class="summary-cards">
      <!-- 步数卡片 -->
      <el-card class="summary-card">
        <div class="card-content">
          <div class="card-icon">
            <i class="el-icon-position"></i>
          </div>
          <div class="card-text">
            <h3>今日步数</h3>
            <p class="card-value">{{ reportData.stepNumber || 0 }} <span>步</span></p>
            <p class="card-compare">
              <span :class="stepDiff >= 0 ? 'positive' : 'negative'">
                <i :class="stepDiff >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ stepDiff >= 0 ? '+' : '' }}{{ stepDiff }}步
              </span>
              较昨日
            </p>
            <el-progress 
              :percentage="Math.min(Math.max((reportData.stepNumber / 10000) * 100, 0), 100)" 
              :format="format"
              :stroke-width="8"
              :show-text="true"
              class="progress-bar">
            </el-progress>
          </div>
        </div>
      </el-card>

      <!-- 睡眠卡片 -->
      <el-card class="summary-card">
        <div class="card-content">
          <div class="card-icon">
            <i class="el-icon-moon-night"></i>
          </div>
          <div class="card-text">
            <h3>睡眠时长</h3>
            <p class="card-value">{{ sleepDuration || '--' }}</p>
            <p class="card-compare">
              <span :class="sleepDiff.includes('+') ? 'positive' : 'negative'">
                <i :class="sleepDiff.includes('+') ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ sleepDiff }}
              </span>
              较昨日
            </p>
            <el-progress 
              :percentage="Math.min(Math.max(sleepQualityScore, 0), 100)" 
              :format="format"
              :stroke-width="8"
              :show-text="true"
              class="progress-bar">
            </el-progress>
          </div>
        </div>
      </el-card>

      <!-- 饮水量卡片 -->
      <el-card class="summary-card">
        <div class="card-content">
          <div class="card-icon">
            <i class="el-icon-water-cup"></i>
          </div>
          <div class="card-text">
            <h3>饮水量</h3>
            <p class="card-value">{{ reportData.waterVolume || 0 }} <span>L</span></p>
            <p class="card-compare">
              <span :class="waterDiff >= 0 ? 'positive' : 'negative'">
                <i :class="waterDiff >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ waterDiff >= 0 ? '+' : '' }}{{ waterDiff }}L
              </span>
              较昨日
            </p>
            <el-progress 
              :percentage="Math.min(Math.max((reportData.waterVolume / 2) * 100, 0), 100)" 
              :format="format"
              :stroke-width="8"
              :show-text="true"
              class="progress-bar">
            </el-progress>
          </div>
        </div>
      </el-card>

      <!-- BMI卡片 -->
      <el-card class="summary-card">
        <div class="card-content">
          <div class="card-icon">
            <i class="el-icon-data-analysis"></i>
          </div>
          <div class="card-text">
            <h3>BMI指数</h3>
            <p class="card-value">{{ reportData.bmi || '--' }}</p>
            <p class="card-compare">
              <span :class="bmiTrend >= 0 ? 'positive' : 'negative'">
                <i :class="bmiTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(bmiTrend) }}%
              </span>
              较上月
            </p>
            <el-progress 
              :percentage="Math.min(Math.max(bmiProgress, 0), 100)" 
              :format="format"
              :stroke-width="8"
              :show-text="true"
              :color="bmiColor"
              class="progress-bar">
            </el-progress>
          </div>
        </div>
      </el-card>

      <!-- 心率卡片 -->
      <el-card class="summary-card">
        <div class="card-content">
          <div class="card-icon">
            <i class="el-icon-warning-outline"></i>
          </div>
          <div class="card-text">
            <h3>平均心率</h3>
            <p class="card-value">{{ reportData.heartRate || '--' }} <span>bpm</span></p>
            <p class="card-compare">
              <span :class="heartRateStatus">{{ heartRateStatusText }}</span>
            </p>
            <el-progress 
              :percentage="Math.min(Math.max(heartRateProgress, 0), 100)" 
              :format="format"
              :stroke-width="8"
              :show-text="true"
              :color="heartRateColor"
              class="progress-bar">
            </el-progress>
          </div>
        </div>
      </el-card>

      <!-- 卡路里卡片 -->
      <el-card class="summary-card">
        <div class="card-content">
          <div class="card-icon">
            <i class="el-icon-fire"></i>
          </div>
          <div class="card-text">
            <h3>卡路里消耗</h3>
            <p class="card-value">{{ reportData.calories || 0 }} <span>kcal</span></p>
            <p class="card-compare">
              <span :class="caloriesTrend >= 0 ? 'positive' : 'negative'">
                <i :class="caloriesTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(caloriesTrend) }}%
              </span>
              较昨日
            </p>
            <el-progress 
              :percentage="Math.min(Math.max((reportData.calories / 2000) * 100, 0), 100)" 
              :format="format"
              :stroke-width="8"
              :show-text="true"
              class="progress-bar">
            </el-progress>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表展示区域 -->
    <div class="chart-container">
      <!-- 步数趋势图（折线图） -->
      <el-card class="chart-card">
        <div slot="header" class="chart-header">
          <span>步数趋势</span>
      <!--     <el-select v-model="stepRange" size="mini" @change="updateStepChart">
            <el-option label="24小时" value="24h"></el-option>
            <el-option label="7天" value="7d"></el-option>
            <el-option label="30天" value="30d"></el-option>
          </el-select>-->
        </div>
        <div class="chart-wrapper">
          <div ref="stepChart" class="chart" style="height: 300px;"></div>
        </div>
      </el-card>

      <!-- 睡眠质量图（饼图+柱状图组合） -->
      <el-card class="chart-card">
        <div slot="header" class="chart-header">
          <span>睡眠质量分析</span>
        </div>
        <div class="chart-wrapper">
          <div class="sleep-charts">
            <div ref="sleepPieChart" class="chart" style="width: 40%; height: 300px;"></div>
            <div ref="sleepBarChart" class="chart" style="width: 60%; height: 300px;"></div>
          </div>
        </div>
      </el-card>

      <!-- 饮水记录（柱状图） -->
      <el-card class="chart-card">
        <div slot="header" class="chart-header">
          <span>饮水记录</span>
          <!-- <el-radio-group v-model="waterViewMode" size="mini" @change="updateWaterChart">
            <el-radio-button label="hourly">按小时</el-radio-button>
            <el-radio-button label="daily">按天</el-radio-button>
          </el-radio-group>-->
        </div>
        <div class="chart-wrapper">
          <div ref="waterChart" class="chart" style="height: 300px;"></div>
        </div>
      </el-card>

      <!-- 健康指标综合图（雷达图） -->
      <el-card class="chart-card">
        <div slot="header" class="chart-header">
          <span>健康指标综合评估</span>
        </div>
        <div class="chart-wrapper">
          <div ref="radarChart" class="chart" style="height: 350px;"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import request  from '@/utils/request.js'
// import { getDailyHealthReport } from '@/api/report'

export default {
  name: 'HealthDashboard',
  data() {
    return {
      reportData: {
        stepNumber: 0,
        waterVolume: 0,
        sleepTime: '',
        wakeupTime: '',
        sbp: null,
        dbp: null,
        weightDiff: 0,
        createTime: '',
        continuousDays: 0,
        deepSleepPercentage: 0,
        lightSleepPercentage: 0,
        remSleepPercentage: 0,
        timeSubHour: 0,
        timeSubMinutes: 0,
        sportTimeLong: 0
      },
      yesterdayData: {
        stepNumber: 0,
        waterVolume: 0,
        timeSubHour: 0,
        timeSubMinutes: 0,
        sportTimeLong: 0
      },
      suggestions: [],
      stepTrend: 0,
      sleepTrend: 0,
      waterTrend: 0,
      bmiTrend: 0,
      caloriesTrend: 0,
      stepRange: '24h',
      waterViewMode: 'hourly',
      stepChart: null,
      sleepPieChart: null,
      sleepBarChart: null,
      waterChart: null,
      radarChart: null
    }
  },
  created(){
    console.log('created')
    this.init()
  },
  computed: {
    reportDate() {
      return new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
    },
    sleepDuration() {
      if (!this.reportData.timeSubHour && !this.reportData.timeSubMinutes) return '--'
      return `${this.reportData.timeSubHour}小时${this.reportData.timeSubMinutes >= 10 ? this.reportData.timeSubMinutes : `0${this.reportData.timeSubMinutes}`}分钟`
    },
    sleepQualityScore() {
      if (!this.reportData.timeSubHour && !this.reportData.timeSubMinutes) return 0
      const sleepHours = this.reportData.timeSubHour || 0
      const sleepMinutes = this.reportData.timeSubMinutes || 0
      const totalSleepMinutes = sleepHours * 60 + sleepMinutes
      // 假设目标睡眠时长为8小时（480分钟）
      const targetSleepMinutes = 480
      // 计算进度百分比，最大100%
      const progress = Math.min((totalSleepMinutes / targetSleepMinutes) * 100, 100)
      return Math.round(progress)
    },
    bmiProgress() {
      const bmi = this.reportData.bmi
      if (!bmi) return 0
      // BMI正常范围是18.5-24.9
      let progress = 0
      if (bmi < 18.5) {
        progress = (bmi / 18.5) * 50
      } else if (bmi > 24.9) {
        progress = 100
      } else {
        progress = ((bmi - 18.5) / (24.9 - 18.5)) * 50 + 50
      }
      // 确保返回值在 0-100 之间
      return Math.min(Math.max(progress, 0), 100)
    },
    bmiColor() {
      const bmi = this.reportData.bmi
      if (!bmi) return '#909399'
      if (bmi < 18.5) return '#E6A23C'
      if (bmi > 24.9) return '#F56C6C'
      return '#67C23A'
    },
    heartRateProgress() {
      const hr = this.reportData.heartRate
      if (!hr) return 0
      // 假设正常心率范围是60-100
      let progress = 0
      if (hr < 60) {
        progress = (hr / 60) * 50
      } else if (hr > 100) {
        progress = 100
      } else {
        progress = ((hr - 60) / (100 - 60)) * 50 + 50
      }
      // 确保返回值在 0-100 之间
      return Math.min(Math.max(progress, 0), 100)
    },
    heartRateColor() {
      const hr = this.reportData.heartRate
      if (!hr) return '#909399'
      if (hr < 60) return '#E6A23C'
      if (hr > 100) return '#F56C6C'
      return '#67C23A'
    },
    heartRateStatus() {
      const hr = this.reportData.heartRate
      if (!hr) return 'normal'
      if (hr < 60) return 'warning'
      if (hr > 100) return 'danger'
      return 'success'
    },
    heartRateStatusText() {
      const hr = this.reportData.heartRate
      if (!hr) return '暂无数据'
      if (hr < 60) return '心率偏低'
      if (hr > 100) return '心率偏高'
      return '心率正常'
    },
    stepDiff() {
      return this.reportData.stepNumber - this.yesterdayData.stepNumber
    },
    waterDiff() {
      return (this.reportData.waterVolume - this.yesterdayData.waterVolume).toFixed(1)
    },
    sleepDiff() {
      const todayMinutes = this.reportData.timeSubHour * 60 + this.reportData.timeSubMinutes
      const yesterdayMinutes = this.yesterdayData.timeSubHour * 60 + this.yesterdayData.timeSubMinutes
      const diffMinutes = todayMinutes - yesterdayMinutes
      const hours = Math.floor(Math.abs(diffMinutes) / 60)
      const minutes = Math.abs(diffMinutes) % 60
      return `${diffMinutes >= 0 ? '+' : '-'}${hours}小时${minutes}分钟`
    }
  },
  mounted() {
    // this.fetchData()
    this.$nextTick(() => {
      this.initCharts()
    })
    
    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
  },
  methods: {
    goToDataLog() {
      this.$router.push('/dataLog');
    },
    init(){
      console.log('init')
      request({
        url: 'gather/UserDay/today',
        method: 'get'
      }).then(res => {
        if (res.data && Array.isArray(res.data)) {
          // 假设第一个是今日，第二个是昨日
          this.reportData = res.data[0] || {}
          this.yesterdayData = res.data[1] || {}
          this.suggestions = res.data.suggestion || []
          this.$nextTick(() => {
            this.updateCharts()
          })
        }
      }).catch(error => {
        console.error('获取数据失败:', error)
      })
    },
    async fetchData() {
      try {
        const res = await getDailyHealthReport()
        this.reportData = res.data
        // 模拟趋势数据
        this.stepTrend = 5.2
        this.sleepTrend = -2.1
        this.waterTrend = 10.5
        
        // 数据更新后刷新图表
        this.updateCharts()
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    
    refreshData() {
      // this.fetchData()
      this.init()
    },
    
    initCharts() {
      // 初始化所有图表
      this.stepChart = echarts.init(this.$refs.stepChart)
      this.sleepPieChart = echarts.init(this.$refs.sleepPieChart)
      this.sleepBarChart = echarts.init(this.$refs.sleepBarChart)
      this.waterChart = echarts.init(this.$refs.waterChart)
      this.radarChart = echarts.init(this.$refs.radarChart)
      
      this.updateCharts()
    },
    
    updateCharts() {
      this.updateStepChart()
      this.updateSleepCharts()
      this.updateWaterChart()
      this.updateRadarChart()
    },
    
    // 步数趋势图（折线图）
    updateStepChart() {
      if (!this.stepChart) return;
      
      const totalSteps = this.reportData?.stepNumber || 0;
      // 生成24小时的数据
      const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`);
      
      // 如果总步数为0，生成全0数据
      if (totalSteps === 0) {
        const stepData = hours.map(() => 0);
        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>{a}: {c} 步'
          },
          xAxis: {
            type: 'category',
            data: hours,
            axisLabel: {
              color: '#606266',
              interval: 3
            }
          },
          yAxis: {
            type: 'value',
            name: '步数',
            axisLabel: {
              color: '#606266'
            }
          },
          series: [{
            name: '步数',
            type: 'line',
            data: stepData,
            smooth: true,
            itemStyle: {
              color: '#409eff'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            }
          }],
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          }
        };
        this.stepChart.setOption(option);
        return;
      }
      
      // 定义活动时间段及其权重
      const timeWeights = [
        { start: 6, end: 9, weight: 0.3 },  // 早晨活动
        { start: 11, end: 14, weight: 0.2 }, // 午间活动
        { start: 17, end: 20, weight: 0.3 }, // 晚间活动
        { start: 20, end: 23, weight: 0.1 }, // 夜间活动
        { start: 0, end: 6, weight: 0.1 }    // 睡眠时间
      ];

      // 生成基础步数数据
      let stepData = hours.map((_, hour) => {
        let baseSteps = 0;
        // 根据时间段分配基础步数
        for (const period of timeWeights) {
          if (hour >= period.start && hour < period.end) {
            baseSteps = totalSteps * period.weight / (period.end - period.start);
            break;
          }
        }
        // 添加随机波动（±20%）
        const variation = baseSteps * 0.2;
        return Math.max(0, baseSteps + (Math.random() * variation * 2 - variation));
      });

      // 调整总步数以匹配实际数据
      const currentTotal = stepData.reduce((sum, steps) => sum + steps, 0);
      const adjustmentFactor = totalSteps / currentTotal;
      stepData = stepData.map(steps => Math.round(steps * adjustmentFactor));
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c} 步'
        },
        xAxis: {
          type: 'category',
          data: hours,
          axisLabel: {
            color: '#606266',
            interval: 3
          }
        },
        yAxis: {
          type: 'value',
          name: '步数',
          axisLabel: {
            color: '#606266'
          }
        },
        series: [{
          name: '步数',
          type: 'line',
          data: stepData,
          smooth: true,
          itemStyle: {
            color: '#409eff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          }
        }],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        }
      };
      this.stepChart.setOption(option);
    },
    
    // 睡眠质量图（饼图+柱状图）
    updateSleepCharts() {
      if (!this.sleepPieChart || !this.sleepBarChart) return
      
      const pieOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}%'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['深睡', '浅睡', 'REM'],
          textStyle: {
            color: '#606266'
          }
        },
        series: [
          {
            name: '睡眠阶段',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: this.reportData.deepSleepPercentage || 0, name: '深睡', itemStyle: { color: '#409eff' } },
              { value: this.reportData.lightSleepPercentage || 0, name: '浅睡', itemStyle: { color: '#67c23a' } },
              { value: this.reportData.remSleepPercentage || 0, name: 'REM', itemStyle: { color: '#e6a23c' } }
            ]
          }
        ]
      }
      this.sleepPieChart.setOption(pieOption)
      
      const barOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['深睡', '浅睡', 'REM'],
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#606266'
          }
        },
        yAxis: {
          type: 'value',
          max: 100,
          name: '百分比',
          axisLabel: {
            color: '#606266'
          }
        },
        series: [
          {
            name: '睡眠质量',
            type: 'bar',
            data: [
              { value: this.reportData.deepSleepPercentage || 0, itemStyle: { color: '#409eff' } },
              { value: this.reportData.lightSleepPercentage || 0, itemStyle: { color: '#67c23a' } },
              { value: this.reportData.remSleepPercentage || 0, itemStyle: { color: '#e6a23c' } }
            ],
            barWidth: '40%',
            label: {
              show: true,
              position: 'top',
              formatter: '{c}%',
              color: '#606266'
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        }
      }
      this.sleepBarChart.setOption(barOption)
    },
    
    // 饮水记录图（柱状图）
    updateWaterChart() {
      if (!this.waterChart) return
      
      const totalWater = this.reportData?.waterVolume || 0
      // 生成24小时的数据
      const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
      
      // 如果总饮水量为0，生成全0数据
      if (totalWater === 0) {
        const waterData = hours.map(() => 0)
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: '{b}<br/>{a}: {c} L'
          },
          xAxis: {
            type: 'category',
            data: hours,
            axisLabel: {
              interval: 3,
              color: '#606266'
            }
          },
          yAxis: {
            type: 'value',
            name: '饮水量(L)',
            axisLabel: {
              color: '#606266'
            }
          },
          series: [{
            name: '饮水量',
            type: 'bar',
            data: waterData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#409eff' },
                { offset: 1, color: '#a0cfff' }
              ])
            },
            barWidth: '60%'
          }],
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          }
        }
        this.waterChart.setOption(option)
        return
      }
      
      // 定义饮水时间段及其权重
      const timeWeights = [
        { start: 7, end: 9, weight: 0.25 },  // 早晨
        { start: 11, end: 13, weight: 0.25 }, // 中午
        { start: 15, end: 17, weight: 0.25 }, // 下午
        { start: 19, end: 21, weight: 0.25 }  // 晚上
      ]

      // 生成基础饮水量数据
      let waterData = hours.map((_, hour) => {
        let baseWater = 0
        // 根据时间段分配基础饮水量
        for (const period of timeWeights) {
          if (hour >= period.start && hour < period.end) {
            baseWater = totalWater * period.weight / (period.end - period.start)
            break
          }
        }
        // 添加随机波动（±30%）
        const variation = baseWater * 0.3
        return Math.max(0, baseWater + (Math.random() * variation * 2 - variation))
      })

      // 调整总饮水量以匹配实际数据
      const currentTotal = waterData.reduce((sum, water) => sum + water, 0)
      const adjustmentFactor = totalWater / currentTotal
      waterData = waterData.map(water => Number((water * adjustmentFactor).toFixed(2)))
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}<br/>{a}: {c} L'
        },
        xAxis: {
          type: 'category',
          data: hours,
          axisLabel: {
            interval: 3,
            color: '#606266'
          }
        },
        yAxis: {
          type: 'value',
          name: '饮水量(L)',
          axisLabel: {
            color: '#606266'
          }
        },
        series: [{
          name: '饮水量',
          type: 'bar',
          data: waterData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#409eff' },
              { offset: 1, color: '#a0cfff' }
            ])
          },
          barWidth: '60%'
        }],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        }
      }
      this.waterChart.setOption(option)
    },
    
    // 健康指标雷达图
    updateRadarChart() {
      if (!this.radarChart) return
      
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          data: ['今日指标'],
          textStyle: {
            color: '#606266'
          }
        },
        radar: {
          indicator: [
            { name: '步数(步)', max: 10000 },
            { name: '睡眠时长(小时)', max: 10 },
            { name: '饮水量(L)', max: 2 },
            { name: '深睡比例(%)', max: 100 },
            { name: '浅睡比例(%)', max: 100 }
          ],
          radius: '65%',
          axisName: {
            color: '#606266'
          },
          splitLine: {
            lineStyle: {
              color: ['#ebeef5']
            }
          }
        },
        series: [{
          name: '健康指标',
          type: 'radar',
          data: [
            {
              value: [
                this.reportData.stepNumber || 0,
                this.reportData.timeSubHour || 0,
                this.reportData.waterVolume || 0,
                this.reportData.deepSleepPercentage || 0,
                this.reportData.lightSleepPercentage || 0
              ],
              name: '今日指标',
              areaStyle: {
                color: 'rgba(64, 158, 255, 0.2)'
              },
              lineStyle: {
                width: 2,
                color: '#409eff'
              }
            }
          ]
        }]
      }
      this.radarChart.setOption(option)
    },
    
    resizeCharts() {
      this.stepChart && this.stepChart.resize()
      this.sleepPieChart && this.sleepPieChart.resize()
      this.sleepBarChart && this.sleepBarChart.resize()
      this.waterChart && this.waterChart.resize()
      this.radarChart && this.radarChart.resize()
    },
    
    generateTimeData(range) {
      // 生成时间轴数据
      if (range === '24h') {
        return Array.from({ length: 24 }, (_, i) => `${i}:00`)
      } else if (range === '7d') {
        return ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      } else {
        return Array.from({ length: 30 }, (_, i) => `第${i + 1}天`)
      }
    },
    
    generateStepData(range) {
      // 生成步数数据
      return [this.reportData.stepNumber || 0]
    },
    format(percentage) {
      // 确保 percentage 是 0-100 之间的数字
      const value = Math.min(Math.max(Number(percentage) || 0, 0), 100)
      return `${Math.round(value)}%`
    }
  }
}
</script>

<style lang="scss" scoped>
.health-dashboard {
  padding: 20px;
  background-color: #f8fafc;
  
  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      margin: 0;
      font-size: 24px;
      color: #2c3e50;
      font-weight: 600;
    }
  }
  
  .summary-cards {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 20px;
    
    @media (max-width: 1200px) {
      grid-template-columns: repeat(2, 1fr);
    }
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
    
    .summary-card {
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      cursor: pointer;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        
        .card-icon {
          transform: scale(1.1);
        }
        
        .card-value {
          color: #409eff;
        }
      }
      
      .card-content {
        display: flex;
        align-items: flex-start;
        padding: 20px;
        
        .card-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          transition: transform 0.3s ease;
          
          i {
            font-size: 24px;
          }
          
          // 为不同卡片设置不同的图标背景色
          &:nth-child(1) {
            background: rgba(103, 194, 58, 0.1);
            i { color: #67c23a; }
          }
          &:nth-child(2) {
            background: rgba(64, 158, 255, 0.1);
            i { color: #409eff; }
          }
          &:nth-child(3) {
            background: rgba(230, 162, 60, 0.1);
            i { color: #e6a23c; }
          }
          &:nth-child(4) {
            background: rgba(144, 147, 153, 0.1);
            i { color: #909399; }
          }
          &:nth-child(5) {
            background: rgba(245, 108, 108, 0.1);
            i { color: #f56c6c; }
          }
          &:nth-child(6) {
            background: rgba(103, 194, 58, 0.1);
            i { color: #67c23a; }
          }
        }
        
        .card-text {
          flex: 1;
          
          h3 {
            margin: 0 0 8px;
            font-size: 16px;
            color: #606266;
            font-weight: 500;
          }
          
          .card-value {
            margin: 0 0 8px;
            font-size: 24px;
            font-weight: 600;
            color: #2c3e50;
            
            span {
              font-size: 14px;
              font-weight: normal;
              color: #909399;
            }
          }
          
          .card-compare {
            margin: 0 0 8px;
            font-size: 14px;
            color: #909399;
            
            .positive {
              color: #67c23a;
            }
            
            .negative {
              color: #f56c6c;
            }
          }
          
          .progress-bar {
            margin-top: 8px;
            
            :deep(.el-progress-bar__outer) {
              background-color: rgba(0, 0, 0, 0.05);
              border-radius: 6px;
            }
            
            :deep(.el-progress-bar__inner) {
              border-radius: 6px;
            }
          }
        }
      }
    }
  }
  
  .chart-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
    gap: 20px;
    
    .chart-card {
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      
      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #ebeef5;
        
        span {
          font-size: 16px;
          font-weight: 500;
          color: #2c3e50;
        }
      }
      
      .chart-wrapper {
        padding: 20px;
        
        .chart {
          width: 100%;
        }
        
        .sleep-charts {
          display: flex;
          align-items: center;
          gap: 20px;
        }
      }
    }
  }
}

// 状态颜色
.warning {
  color: #e6a23c;
}

.danger {
  color: #f56c6c;
}

.success {
  color: #67c23a;
}

.normal {
  color: #909399;
}

// 图表颜色
:deep(.echarts) {
  .chart-line {
    stroke: #409eff;
  }
  
  .chart-area {
    fill: rgba(64, 158, 255, 0.1);
  }
  
  .chart-bar {
    fill: #67c23a;
  }
}
</style>